package com.ruoyi.common.utils.order;


import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @author admin
 */
@Component
public class WeixinUtil {

	/**
	 * 方法名：byteToHex</br>
	 * 详述：字符串加密辅助方法 </br>
	 * 开发人员：souvc  </br>
	 * 创建时间：2016-1-5  </br>
	 * @param hash
	 * @return 说明返回值含义
	 */
	private static String byteToHex(final byte[] hash) {
		Formatter formatter = new Formatter();
		for (byte b : hash) {
			formatter.format("%02x", b);
		}
		String result = formatter.toString();
		formatter.close();
		return result;

	}

	/**
	 * 方法名：getWxConfig</br>
	 * 详述：获取微信的配置信息 </br>
	 * 开发人员：souvc  </br>
	 * 创建时间：2016-1-5  </br>
	 * @return 说明返回值含义
	 */
	public static Map<String, Object> getWxConfig(String appId,String secret,String requestUrl) {
		Map<String, Object> ret = new HashMap<String, Object>();
		String access_token = "";
		String jsapi_ticket = "";
		String timestamp = Long.toString(System.currentTimeMillis() / 1000); // 必填，生成签名的时间戳
		String nonceStr = UUID.randomUUID().toString(); // 必填，生成签名的随机串
		String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + secret;

		String jsonStr = HttpClientUtil.sendGetRequest(url, null, null);

		if (jsonStr != null) {

			JSONObject json = (JSONObject) JSONObject.parseObject(jsonStr);
			//要注意，access_token需要缓存
			access_token = json.getString("access_token");

			url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi";
			String jsonStr1 = HttpClientUtil.sendGetRequest(url, null, null);
			if (jsonStr1 != null) {
				json = (JSONObject) JSONObject.parseObject(jsonStr1);
				jsapi_ticket = json.getString("ticket");
			}
		}
		String signature = "";
		// 注意这里参数名必须全部小写，且必须有序
		String sign = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonceStr+ "&timestamp =" + timestamp + "&url=" + requestUrl;
		try {
			MessageDigest crypt = MessageDigest.getInstance("SHA-1");
			crypt.reset();
			crypt.update(sign.getBytes("UTF-8"));
			signature = byteToHex(crypt.digest());
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		ret.put("appId", appId);
		ret.put("timestamp", timestamp);
		ret.put("nonceStr", nonceStr);
		ret.put("signature", signature);
		return ret;
	}

    public static String getOpenCode(String appid, String secret, String code) {

		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid  + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
		String jsonstr = HttpClientUtil.sendGetRequest(url, null, null);
		JSONObject jsonObject =JSONObject.parseObject(jsonstr);
		if (null  != jsonObject)
		{
			if (null != jsonObject.getString("openid"))
			{
				return  jsonObject.getString("openid");
			}else {
				return  jsonObject.getString("errmsg");
			}

		}
		return "";
	}

	public static AjaxResult getOpenCodeForAjax(String appid, String secret, String code) {

		String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appid  + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
		String jsonstr = HttpClientUtil.sendGetRequest(url, null, null);
		JSONObject jsonObject =JSONObject.parseObject(jsonstr);
		if (null  != jsonObject)
		{
			if (null != jsonObject.getString("openid"))
			{
				return  AjaxResult.success(jsonObject.getString("openid"));
			}else {
				return  AjaxResult.error(jsonObject.getString("errmsg"));
			}

		}
		return new AjaxResult();
	}
}
